package com.david.flowable.service.Impl;

import com.david.common.exception.FlowException;
import com.david.common.utils.PageResult;
import com.david.flowable.FlowComment;
import com.david.flowable.flowfactory.FlowServiceFactory;
import com.david.flowable.mapper.FlowFormMapper;
import com.david.flowable.pojo.dto.FlowCommentDTO;
import com.david.flowable.pojo.dto.FlowTaskDTO;
import com.david.flowable.pojo.dto.FormFlowDTO;
import com.david.flowable.pojo.vo.FlowQueryVO;
import com.david.flowable.pojo.vo.FlowTaskVO;
import com.david.flowable.service.FlowTaskService;
import com.david.flowable.utils.DateUtils;
import com.david.flowable.utils.FlowUtils;
import com.david.system.mapper.UserMapper;
import com.david.system.pojo.Entity.DeptEntity;
import com.david.system.pojo.Entity.UserEntity;
import com.david.system.pojo.Entity.UserInfo;
import com.github.pagehelper.PageHelper;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

import static com.david.common.utils.ResultUtils.fail;
import static com.david.common.utils.ResultUtils.success;

@Service
public class FlowTaskServiceImpl extends FlowServiceFactory implements FlowTaskService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FlowFormMapper flowFormMapper;

    /**
    * @Description: 完成任务
    * @Param: [flowTaskVO]
    * @return: org.springframework.http.ResponseEntity<java.lang.Object>
    * @Author: david
    * @Date: 2024/8/8
    */
    @Override
    public ResponseEntity<Object> complete(FlowTaskVO flowTaskVO) {
        System.out.println(LocalDateTime.now());
        Task task = taskService.createTaskQuery().taskId(flowTaskVO.getTaskId()).singleResult();
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntity userEntity = userMapper.selectUserByUsername(username);
        if (Objects.isNull(task)){
            return fail(true, "任务不存在");
        } else {
            taskService.addComment(flowTaskVO.getTaskId(), flowTaskVO.getInstanceId(), flowTaskVO.getComment());
            taskService.setAssignee(flowTaskVO.getTaskId(), userEntity.getId().toString());
            taskService.complete(flowTaskVO.getTaskId(), flowTaskVO.getVariables());
            return success(true, "任务完成");
        }
    }

    /**
    * @Description: 获取待办列表
    * @Param: [flowQueryVO]
    * @return: com.david.common.utils.PageResult
    * @Author: david
    * @Date: 2024/8/8
    */
    @Override
    public PageResult todolist(FlowQueryVO flowQueryVO) {

        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntity currentUser = userMapper.selectUserByUsername(username);
//        TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(currentUser.getId().toString()).taskCandidateGroup(currentUser.getJobId().toString())
//                .taskCreatedAfter(DateUtils.getDate(flowQueryVO.getStartDate())).taskCreatedBefore(DateUtils.getDate(flowQueryVO.getEndDate())).orderByTaskCreateTime().desc();
        TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(currentUser.getId().toString())
                .taskCreatedAfter(DateUtils.getDate(flowQueryVO.getStartDate())).taskCreatedBefore(DateUtils.getDate(flowQueryVO.getEndDate())).orderByTaskCreateTime().desc();
        List<Task> list = taskQuery.listPage((flowQueryVO.getPage()-1)* flowQueryVO.getPageSize(), flowQueryVO.getPageSize() );
        System.out.println(list);
        List<FlowTaskDTO> flowTaskDTOS = new ArrayList<>();
        for(Task task : list){
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
            HistoricProcessInstance hp = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            List<FormFlowDTO> formFlowDTOS = flowFormMapper.selectFormFlow(FormFlowDTO.builder().flowId(hp.getProcessDefinitionId()).build());

            // Important hp的startUserID = 实为发起者的username
            UserEntity startUser = userMapper.selectUserByUsername(hp.getStartUserId());
            // 当前流程信息
            FlowTaskDTO flowTaskDTO = FlowTaskDTO.builder()
                    // 当前流程信息
                    .taskId(task.getId())
                    .taskDefKey(task.getTaskDefinitionKey())
                    .createTime(DateUtils.getLocalDateTime(task.getCreateTime()))
                    .procDefId(task.getProcessDefinitionId())
                    .executionId(task.getExecutionId())
                    .taskName(task.getName())
                    .isClaim(Objects.nonNull(task.getClaimTime()))
                    // 流程定义信息
                    .deployId(pd.getDeploymentId())
                    .procDefName(pd.getName())
                    .procDefVersion(pd.getVersion())
                    .procInsId(task.getProcessInstanceId())
                    .category(pd.getCategory())
                    // 发起人信息
                    .startUserId(startUser.getId().toString())
                    .startUserName(startUser.getName())
                    .build();
            if (!formFlowDTOS.isEmpty()){
                FormFlowDTO currentFormFlow = formFlowDTOS.get(0);
                // 关系表名称
                flowTaskDTO.setFormflowName(currentFormFlow.getProcessName());
            }
            flowTaskDTOS.add(flowTaskDTO);
        }
        PageResult pageResult = new PageResult();
        pageResult.setTotal((int) taskQuery.count());
        pageResult.setRecords(flowTaskDTOS);
        return pageResult;
    }

    @Override
    public PageResult finishedlist(FlowQueryVO flowQueryVO) {
        PageHelper.startPage(flowQueryVO.getPage(), flowQueryVO.getPageSize());
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntity userEntity = userMapper.selectUserByUsername(username);
        List<FlowTaskDTO> flowTaskDTOS = new ArrayList<>();
        HistoricTaskInstanceQuery instanceQuery = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(userEntity.getId().toString())
                .finished()
                .orderByHistoricTaskInstanceEndTime()
                .desc();

        List<HistoricTaskInstance> instanceList = instanceQuery.listPage((flowQueryVO.getPage() - 1) * flowQueryVO.getPageSize(), flowQueryVO.getPageSize());
        for (HistoricTaskInstance instance : instanceList){
            HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(instance.getProcessInstanceId()).singleResult();
            Task currenttask = taskService.createTaskQuery().processInstanceId(instance.getProcessInstanceId()).singleResult();
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(instance.getProcessDefinitionId()).singleResult();
            List<FormFlowDTO> formFlowDTOS = flowFormMapper.selectFormFlow(FormFlowDTO.builder().flowId(hpi.getProcessDefinitionId()).build());
            FlowTaskDTO flowtaskDTO = FlowTaskDTO.builder()

//                    以下为已完成的最新任务信息
//                    .taskId(instance.getId())
//                    .taskName(instance.getName())
//                    .taskDefKey(instance.getTaskDefinitionKey())
                    .createTime(DateUtils.getLocalDateTime(hpi.getStartTime()))
                    .finishTime(DateUtils.getLocalDateTime(hpi.getEndTime()))
                    .duration(DateUtils.getDuration(instance.getDurationInMillis()))
                    .procInsId(instance.getProcessInstanceId())
                    .build();
            if (!formFlowDTOS.isEmpty()){
                FormFlowDTO currentFormFlow = formFlowDTOS.get(0);
                // 关系表名称
                flowtaskDTO.setFormflowName(currentFormFlow.getProcessName());
            }
            if(!Objects.isNull(currenttask)){
                flowtaskDTO.setTaskId(currenttask.getId());
                flowtaskDTO.setTaskName(currenttask.getName());
                flowtaskDTO.setTaskDefKey(currenttask.getTaskDefinitionKey());
            } else {
                flowtaskDTO.setTaskName("已完成审批");
            }
            if (!Objects.isNull(pd)){
                flowtaskDTO.setProcDefVersion(pd.getVersion());
                flowtaskDTO.setProcDefName(pd.getName());
                flowtaskDTO.setProcDefKey(pd.getKey());
                flowtaskDTO.setCategory(pd.getCategory());
                flowtaskDTO.setDeployId(pd.getDeploymentId());
            }
            if (!Objects.equals(instance.getAssignee(), "")){
                List<UserInfo> startUser = userMapper.selectUserByIds(List.of(Long.parseLong(instance.getAssignee())));
                flowtaskDTO.setStartUserName(startUser.get(0).getName());
                flowtaskDTO.setStartUserId(instance.getAssignee());
                flowtaskDTO.setStartDeptName(startUser.get(0).getDept());
            }
            flowTaskDTOS.add(flowtaskDTO);
        }
        PageResult result = PageResult.builder().total((int) instanceQuery.count()).records(flowTaskDTOS).build();
        return result;
    }



    /**
    * @Description: 任务驳回，不考虑子流程
    * @Param: [flowTaskVO]
    * @return: void
    * @Author: david
    * @Date: 2024/8/8
    */
    @Override
    public void reject(FlowTaskVO flowTaskVO) {
        boolean suspended = taskService.createTaskQuery().taskId(flowTaskVO.getTaskId()).singleResult().isSuspended();
        if (suspended){
            throw new FlowException("流程已挂起，暂停执行");
        }
        Task task = taskService.createTaskQuery().taskId(flowTaskVO.getTaskId()).singleResult();
        System.out.println("发起任务:"+ task);
        List<Task> list = taskService.createTaskQuery().processInstanceId(flowTaskVO.getInstanceId()).list();
        System.out.println("当前任务列表：");
        System.out.println(list);
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
        System.out.println(processDefinition);
        Process process = repositoryService.getBpmnModel(processDefinition.getId()).getProcesses().get(0);
        List<String> targetIds = new ArrayList<>();
        // 不考虑子流程
        Collection<FlowElement> flowElements = process.getFlowElements();
        for (FlowElement flowElement : flowElements){
            String id = flowElement.getId();
            List<SequenceFlow> incomingFlows = null ;
            if(task.getTaskDefinitionKey().equals(id)){
                incomingFlows = FlowUtils.getElementIncomingFlows(flowElement);
                System.out.println("==================");
                System.out.println(id+"的incomingFlow:"+incomingFlows);

                for (SequenceFlow sequenceFlow : incomingFlows){
                    FlowElement sourceFlowElement = sequenceFlow.getSourceFlowElement();
                    if (sourceFlowElement instanceof UserTask){
                        targetIds.add(sourceFlowElement.getId());
                    }
                }
            }
        }
        System.out.println(targetIds);
        if (!targetIds.isEmpty()){
            taskService.addComment(flowTaskVO.getTaskId(),flowTaskVO.getInstanceId(), FlowComment.REJECT.getType(),flowTaskVO.getComment());
            // moveSingleActivityIdToActivityIds的参数为task的taskDefinitionKey，flowelement的id
            runtimeService.createChangeActivityStateBuilder().processInstanceId(flowTaskVO.getInstanceId()).moveSingleActivityIdToActivityIds(task.getTaskDefinitionKey(),targetIds).changeState();
            List<Task> list2 = taskService.createTaskQuery().processInstanceId(flowTaskVO.getInstanceId()).list();
            System.out.println("驳回后任务：");
            System.out.println(list2);
        } else {
            throw new FlowException("任务无法驳回");
        }

    }

    @Override
    public List<FlowTaskDTO> records(String procInsId) {
        Map<String,Object> map = new HashMap<>();
        List<FlowTaskDTO> flowTaskDTOList = new ArrayList<>();
        if (procInsId!=null){
            List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInsId).finished().orderByHistoricActivityInstanceStartTime().desc().list();
            for (HistoricActivityInstance instance : list){
//                System.out.println(instance);
                System.out.println(instance.getActivityId()+instance.getActivityType()+instance.getActivityName());
                FlowTaskDTO startFlowtaskDTO = new FlowTaskDTO();
                FlowTaskDTO flowTaskDTO = new FlowTaskDTO();

                if (instance.getActivityType().equals("userTask")){
                    flowTaskDTO.setTaskName(instance.getActivityName());
                    flowTaskDTO.setTaskDefKey(instance.getActivityId());
                    flowTaskDTO.setCreateTime(DateUtils.getLocalDateTime(instance.getStartTime()));
                    flowTaskDTO.setFinishTime(DateUtils.getLocalDateTime(instance.getEndTime()));
                    flowTaskDTO.setDuration(DateUtils.getDuration(instance.getDurationInMillis()));
                    if (instance.getAssignee()!=null){
                        List<Long> ids = List.of(Long.parseLong(instance.getAssignee()));
                        System.out.println(ids);
                        UserInfo userInfo = userMapper.selectUserByIds(ids).get(0);
                        flowTaskDTO.setAssigneeId(Long.parseLong(instance.getAssignee()));
                        flowTaskDTO.setAssigneeName(userInfo.getName());
                        flowTaskDTO.setAssigneeDeptName(userInfo.getDept());
                    }
                    List<Comment> comments = taskService.getProcessInstanceComments(instance.getProcessInstanceId());
                    for (Comment comment : comments){
                        if (comment.getTaskId().equals(instance.getTaskId())){
                            flowTaskDTO.setComment(FlowCommentDTO.builder().type(comment.getType()).comment(comment.getFullMessage()).build());
                        }
                    }
                    System.out.println(flowTaskDTO);
                    flowTaskDTOList.add(flowTaskDTO);
                }
                if (instance.getActivityType().equals("startEvent")){
//                    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).singleResult();
                    HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).singleResult();
//                    System.out.println("userId比较1:"+hpi.getStartUserId());
//                    System.out.println("userId比较2:"+processInstance.getStartUserId());
                    String startUserId =hpi.getStartUserId();
                    UserEntity startUser = userMapper.selectUserByUsername(startUserId);
                    startFlowtaskDTO.setAssigneeName(startUser.getName());
                    startFlowtaskDTO.setStartUserId(startUser.getId().toString());
                    DeptEntity deptEntity = userMapper.selectDepById(startUser.getDeptId());
                    startFlowtaskDTO.setAssigneeDeptName(deptEntity.getName());
                    startFlowtaskDTO.setTaskName("发起申请");
                    startFlowtaskDTO.setCreateTime(DateUtils.getLocalDateTime(instance.getStartTime()));
                    flowTaskDTOList.add(startFlowtaskDTO);
                }
            }

        }

        return flowTaskDTOList;
    }

    @Override
    public void revoke(FlowTaskVO flowTaskVO) {
        Task task = taskService.createTaskQuery().processInstanceId(flowTaskVO.getInstanceId()).singleResult();
        if(task == null){
            throw new FlowException("流程不存在，无法撤回");
        }
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(flowTaskVO.getInstanceId())
                .orderByTaskCreateTime()
                .desc().list();
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntity currentUser = userMapper.selectUserByUsername(username);
        String myTaskId = null;
        HistoricTaskInstance myTask = null;
//        撤回任务至当前用户最近的节点
        for (HistoricTaskInstance instance : list){
            if(instance.getAssignee().equals(currentUser.getId().toString())){
                myTask = instance;
                break;
            }
        }
        if (myTask == null){
            throw new FlowException("非当前用户流程，无法撤回");
        }
        taskService.addComment(task.getId(),flowTaskVO.getInstanceId(),FlowComment.REVOKE.getType(),FlowComment.REVOKE.getRemark());
        runtimeService.createChangeActivityStateBuilder().processInstanceId(flowTaskVO.getInstanceId()).moveActivityIdTo(task.getTaskDefinitionKey(),myTask.getTaskDefinitionKey()).changeState();
    }

    @Override
    public PageResult getMyProcess(FlowQueryVO flowQueryVO) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
//        UserEntity currentUser = userMapper.selectUserByUsername(username);
        List<HistoricProcessInstance> hpiList = historyService.createHistoricProcessInstanceQuery()
                .startedBy(username).orderByProcessInstanceStartTime().desc()
                .listPage((flowQueryVO.getPage()-1)*flowQueryVO.getPageSize(),flowQueryVO.getPageSize());
        List<FlowTaskDTO> flowTaskDTOList = new ArrayList<>();
        for (HistoricProcessInstance hpi : hpiList){
            // 当前任务(事实上可能有两个审批流程并行，这里先考虑只显示一个）
            Task currentTask = taskService.createTaskQuery().processInstanceId(hpi.getId()).singleResult();
            List<FormFlowDTO> formFlowDTOS = flowFormMapper.selectFormFlow(FormFlowDTO.builder().flowId(hpi.getProcessDefinitionId()).build());
            FlowTaskDTO flowTaskDTO = FlowTaskDTO.builder().procDefKey(hpi.getProcessDefinitionKey())
                    // 流程历史信息
                    .procDefId(hpi.getProcessDefinitionId())
                    .procDefName(hpi.getProcessDefinitionName())
                    .category(hpi.getProcessDefinitionCategory())
                    .procDefVersion(hpi.getProcessDefinitionVersion())
                    .deployId(hpi.getDeploymentId())
                    .procInsId(hpi.getId())
                    .createTime(DateUtils.getLocalDateTime(hpi.getStartTime()))
                    .finishTime(DateUtils.getLocalDateTime(hpi.getEndTime()))
                    .duration(DateUtils.getDuration(hpi.getDurationInMillis())).build();
            if (!formFlowDTOS.isEmpty()){
                FormFlowDTO currentFormFlow = formFlowDTOS.get(0);
                // 关系表名称
                flowTaskDTO.setFormflowName(currentFormFlow.getProcessName());
            }
            // 当前任务信息(如果已完成，可能没有)
            if (!Objects.isNull(currentTask)){
                flowTaskDTO.setTaskId(currentTask.getId());
                flowTaskDTO.setTaskName(currentTask.getName());
                if (!Objects.isNull(currentTask.getAssignee())){
                    UserInfo assigneeUser = userMapper.selectUserByIds(List.of(Long.parseLong(currentTask.getAssignee()))).get(0);
                    flowTaskDTO.setAssigneeId(assigneeUser.getId());
                    flowTaskDTO.setAssigneeName(assigneeUser.getName());
                    flowTaskDTO.setAssigneeDeptName(assigneeUser.getDept());
                }

            }
            flowTaskDTOList.add(flowTaskDTO);


        }
        // 流程信息
        PageResult result = PageResult.builder().total(hpiList.size()).records(flowTaskDTOList).build();
        return result;
    }

    @Override
    public void stopProcIns(String procInsId) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).startedBy(username).singleResult();
        if(Objects.isNull(pi)){
            throw new FlowException("取消申请失败，流程已完成");
        } else {
            Collection<FlowElement> flowElements = repositoryService.getBpmnModel(pi.getProcessDefinitionId()).getProcesses().get(0).getFlowElements();
            List<FlowElement> endNodeList = flowElements.stream().filter(flowElement -> flowElement instanceof EndEvent).toList();
            if (endNodeList.isEmpty()){
                throw new FlowException("取消申请失败，流程无结束节点");
            } else {
                Task currentTask = taskService.createTaskQuery().processInstanceId(procInsId).singleResult();
                List<String> list = endNodeList.stream().map(flowElement -> flowElement.getId()).toList();

                runtimeService.createChangeActivityStateBuilder().processInstanceId(procInsId).moveSingleActivityIdToActivityIds(currentTask.getTaskDefinitionKey(),list).changeState();
            }

        }
    }

    @Override
    public void removeProcIns(String procInsId) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).startedBy(username).singleResult();
        if(Objects.isNull(pi)){
            throw new FlowException("删除失败");
        } else {
            runtimeService.deleteProcessInstance(procInsId,"发起者删除");

        }
    }

    @Override
    public PageResult getCandidateList(FlowQueryVO flowQueryVO) {
        //考虑两种情况，一种候选人，一种候选岗位
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntity currentUser = userMapper.selectUserByUsername(username);
        List<Task> candidatelist = taskService.createTaskQuery().taskCandidateUser(currentUser.getId().toString()).taskCandidateGroup(currentUser.getJobId().toString()).orderByTaskCreateTime().desc()
                .listPage((flowQueryVO.getPage()-1)*flowQueryVO.getPageSize(),flowQueryVO.getPageSize());
        List<FlowTaskDTO> candidateTasks = new ArrayList<>();
        for(Task task : candidatelist){
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
            HistoricProcessInstance hp = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            List<FormFlowDTO> formFlowDTOS = flowFormMapper.selectFormFlow(FormFlowDTO.builder().flowId(hp.getProcessDefinitionId()).build());

            // Important hp的startUserID = 实为发起者的username
            UserEntity startUser = userMapper.selectUserByUsername(hp.getStartUserId());
            // 当前流程信息
            FlowTaskDTO flowTaskDTO = FlowTaskDTO.builder()
                    // 当前流程信息
                    .taskId(task.getId())
                    .taskDefKey(task.getTaskDefinitionKey())
                    .createTime(DateUtils.getLocalDateTime(task.getCreateTime()))
                    .procDefId(task.getProcessDefinitionId())
                    .executionId(task.getExecutionId())
                    .taskName(task.getName())
                    // 流程定义信息
                    .deployId(pd.getDeploymentId())
                    .procDefName(pd.getName())
                    .procDefVersion(pd.getVersion())
                    .procInsId(task.getProcessInstanceId())
                    .category(pd.getCategory())
                    // 发起人信息
                    .startUserId(startUser.getId().toString())
                    .startUserName(startUser.getName())
                    .build();
            if (!formFlowDTOS.isEmpty()){
                FormFlowDTO currentFormFlow = formFlowDTOS.get(0);
                // 关系表名称
                flowTaskDTO.setFormflowName(currentFormFlow.getProcessName());
            }
            candidateTasks.add(flowTaskDTO);
        }
        PageResult result = PageResult.builder().total(candidatelist.size()).records(candidateTasks).build();
        return result;
    }

    @Override
    public String claimTask(String taskId) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntity currentUser = userMapper.selectUserByUsername(username);
        Task task = taskService.createTaskQuery().taskCandidateUser(currentUser.getId().toString()).taskCandidateGroup(currentUser.getJobId().toString()).taskId(taskId).singleResult();
        if(Objects.isNull(task)){
            return "任务无法认领";
        } else if (Objects.nonNull(task.getAssignee())){
            return "任务已被认领，无法重复认领";
        } else {
            taskService.claim(taskId,currentUser.getId().toString());
            return "已认领";
        }
    }

    @Override
    public String unclaimTask(String taskId) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        UserEntity currentUser = userMapper.selectUserByUsername(username);
        Task task = taskService.createTaskQuery().taskId(taskId).taskAssignee(currentUser.getId().toString()).singleResult();
        if (Objects.isNull(task)){
            return "非当前用户认领任务，或任务未认领，无法取消认领";
        } else {
            taskService.unclaim(taskId);
            return "已取消认领";
        }
    }

}
